package com.szgr.baoyin.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.lidroid.xutils.BitmapUtils;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.szgr.baoyin.MyApplication;
import com.szgr.baoyin.R;
import com.szgr.baoyin.utils.Constant;
import com.szgr.baoyin.utils.DialogUtils;
import com.szgr.baoyin.utils.MyTool;
import com.szgr.baoyin.utils.ToastUtils;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

public class MyAccountActivity extends BaseActivity {

    private Dialog menuDialog;
    private String imagePath;
    private ImageView img_head;
    private View acHead;
    private View acNick;
    private View acPass;
    private TextView tv_name;
    private String modifyNick;
    private String modifyPassword;
    private TextView tv_pass;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 300:
                    DialogUtils.hideLoadingDialog();
                    ToastUtils.showToast((String) msg.obj);
                    break;
                case 400:
                    DialogUtils.hideLoadingDialog();

                    if (isModifyPass) {
                        ToastUtils.showToast("密码修改成功，请重新登录");
                        MyApplication.getmInstance().clearLoginMessage();
                        startActivity(new Intent(MyAccountActivity.this, LoginActivity.class));
                        finish();
                    } else if(isModifyIcon){
                        InputStream imageStream = null;
                        try {
                            imageStream = getContentResolver().openInputStream(selectedImage);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
                        try {
                            imageStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        img_head.setImageBitmap(yourSelectedImage);
                    }
                    break;
                case 401:
                    MyApplication.getmInstance().clearLoginMessage();
                    startActivity(new Intent(MyAccountActivity.this, LoginActivity.class));
                    finish();
                    break;
            }
        }
    };
    private boolean isModifyPass = false;
    private boolean isModifyIcon = false;
    private Uri selectedImage;
    private String image_copy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_my_account);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initActionBar() {
        actionBarTitle.setText("我的账户");
//        actionBarConfirm.setVisibility(View.VISIBLE);
//        actionBarConfirm.setText("修改");
    }

    @Override
    public void initView() {
        image_copy = MyTool.getSavePath(getApplicationContext()) + "/image_copy.jpg";

        acHead = findViewById(R.id.account_head_view);
        acHead.setOnClickListener(this);
        acNick = findViewById(R.id.account_nick);
        acNick.setOnClickListener(this);
        findViewById(R.id.account_sex).setOnClickListener(this);
        acPass = findViewById(R.id.account_password);
        acPass.setOnClickListener(this);
        findViewById(R.id.account_address).setOnClickListener(this);
        findViewById(R.id.exit).setOnClickListener(this);

        img_head = (ImageView) findViewById(R.id.account_head);
        tv_name = (TextView) findViewById(R.id.account_name);
        tv_pass = (TextView) findViewById(R.id.account_pass);

        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("username")) {
            String username = intent.getStringExtra("username");
            String usericon = intent.getStringExtra("usericon");
            MyTool.showPicture(this, img_head, usericon);
            tv_name.setText(username);
        }

        View view = LayoutInflater.from(this).inflate(R.layout.layout_my_account_dialog, null, false);
        view.findViewById(R.id.account_paizhao).setOnClickListener(this);
        view.findViewById(R.id.account_choose).setOnClickListener(this);
        view.findViewById(R.id.account_cancel).setOnClickListener(this);
        menuDialog = MyTool.getMenuDialog(this, view);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.action_bar_left:
                finish();
                break;
            case R.id.account_head_view:
                menuDialog.show();
                break;
            case R.id.account_nick:
                Intent nickIntent = new Intent(this, EditActivity.class);
                nickIntent.putExtra("where", "nick");
                startActivityForResult(nickIntent, 333);
                break;
            case R.id.account_sex:
                break;
            case R.id.account_password:
                Intent passIntent = new Intent(this, EditActivity.class);
                passIntent.putExtra("where", "pass");
                startActivityForResult(passIntent, 334);
                break;
            case R.id.account_address:
                startActivity(new Intent(this, AddressActivity.class));
                break;
            case R.id.account_paizhao:
                menuDialog.dismiss();
                Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                String savePath = MyTool.getSavePath(getApplicationContext());
                Uri imageUri = Uri.fromFile(new File(savePath, "image.jpg"));
                intent1.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent1, 331);
                break;
            case R.id.account_choose:
                menuDialog.dismiss();
                Intent intent2 = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                intent2.setType("image/*");
//                intent2.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent2, 332);
                break;
            case R.id.account_cancel:
                menuDialog.dismiss();
                break;
            case R.id.action_bar_confirm:
                if (!(imagePath == null && modifyNick == null && modifyPassword == null)) {
//                    if(modifyPassword == null){
//                        modifyPassword = "";
//                    }
//                    if(modifyNick == null){
//                        modifyNick = "";
//                    }
                    modifyAccount(modifyPassword, modifyNick);
                } else {
                    ToastUtils.showToast("请修改账户资料");
                }
                break;
            case R.id.exit:
                exitApp();
                break;
        }
    }

    /**
     * 退出登录
     */
    private void exitApp() {
        StringRequest sr = new StringRequest(Request.Method.POST, Constant.URL_EXIT,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        System.out.println("-----exit---->" + s);
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            Object datas = jsonObject.get("datas");
                            if (datas instanceof String) {
                                String result = (String) datas;
                                if ("1".equals(result)) {
                                    mHandler.obtainMessage(401).sendToTarget();
                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("key", MyApplication.getmInstance().getKey());
                map.put("username", MyApplication.getmInstance().getUserPhone());
                map.put("client", "android");
                return map;
            }
        };
        MyApplication.getmInstance().addToRequestQueue(sr);
    }

    /**
     * 修改用户信息
     */
    private void modifyAccount(String passwordNew, String name) {
        DialogUtils.showLoadingDialog(this, "正在修改中...", true);
        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(60 * 1000);
        RequestParams params = new RequestParams();

        if (passwordNew != null) {
            params.put("password_new", passwordNew);
            params.put("password", MyApplication.getmInstance().getPassword());
            isModifyPass = true;
        }else{
            isModifyPass = false;
        }
        if (name != null) {
            params.put("member_truename", name);
        }
        params.put("key", MyApplication.getmInstance().getKey());
        try {
            if (imagePath != null) {
                InputStream imageStream = null;
                try {
                    imageStream = getContentResolver().openInputStream(selectedImage);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
                imagePath = MyTool.compressImage(yourSelectedImage,2024,image_copy);
                params.put("member_avatar", new File(imagePath));
                isModifyIcon = true;
            }else{
                isModifyIcon = false;
            }
//            params.put("member_avatar", new File(imagePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        client.post(Constant.URL_EDIT_MSG, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                if (response != null) {
                    System.out.println("---pass--->" + response.toString());
                    try {
                        JSONObject datas = response.getJSONObject("datas");
                        if (datas.has("error")) {
                            String error = datas.getString("error");
                            mHandler.obtainMessage(300, error).sendToTarget();
                        } else if (datas.has("result")) {
                            String result = datas.getString("result");
                            if ("1".equals(result)) {
                                mHandler.obtainMessage(400).sendToTarget();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Throwable e, JSONObject errorResponse) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case 332:
                if (resultCode == RESULT_OK) {
                    selectedImage = data.getData();
                    Cursor cursor = getContentResolver().query(selectedImage, null, null, null, null);
                    if (cursor == null) {
                        ToastUtils.showToast("图片无效");
                    } else {
                        cursor.moveToFirst();
                        imagePath = cursor.getString(1);
//                            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
////                        img_head.setImageBitmap(bitmap);
//                            Bitmap bitmap1 = MyTool.getBitmapByBytes(MyTool.Bitmap2Bytes(bitmap), 900, 900);
//                            img_head.setImageBitmap(bitmap1);
                        cursor.close();

                        modifyAccount(null, null);
                    }
//                    InputStream imageStream = null;
//                    try {
//                        imageStream = getContentResolver().openInputStream(selectedImage);
//                    } catch (FileNotFoundException e) {
//                        e.printStackTrace();
//                    }
//                    Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
//                    try {
//                        imageStream.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                    img_head.setImageBitmap(yourSelectedImage);
                }
                break;
            case 331:
                if (resultCode == RESULT_OK) {
//                        Bitmap data1 = BitmapFactory.decodeFile(MyTool.getSavePath(getApplicationContext()) + "/image.jpg");
//                        String savePath = MyTool.getSavePath(getApplicationContext());
                    imagePath = MyTool.getSavePath(getApplicationContext()) + "/image.jpg";
                    modifyAccount(null, null);
//                    Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
                    selectedImage = Uri.fromFile(new File(imagePath));
//                        Uri selectedImage = data.getData();
//                    InputStream imageStream = null;
//                    try {
//                        imageStream = getContentResolver().openInputStream(selectedImage);
//                    } catch (FileNotFoundException e) {
//                        e.printStackTrace();
//                    }
//                    Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
//                    try {
//                        imageStream.close();
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                    img_head.setImageBitmap(yourSelectedImage);
                }
                break;
            case 333:
                if (data != null) {
                    modifyNick = data.getStringExtra("content");
                    tv_name.setText(modifyNick);
                    imagePath = null;
                    modifyAccount(null, modifyNick);
                }
                break;
            case 334:
                if (data != null) {
                    modifyPassword = data.getStringExtra("content");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < modifyPassword.length(); i++) {
                        sb.append("*");
                    }
                    tv_pass.setText(sb.toString());
                    imagePath = null;
                    modifyAccount(modifyPassword, null);
                }
                break;
        }

    }

    private Bitmap decodeUri(Uri selectedImage) throws FileNotFoundException {

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o);

        // The new size we want to scale to
        final int REQUIRED_SIZE = 140;

        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
//            if (width_tmp / 2 < REQUIRED_SIZE
//                    || height_tmp / 2 < REQUIRED_SIZE) {
//                break;
//            }
            if (height_tmp * bitmap.getRowBytes() < 1024 * 1024) {

                break;
            }
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(getContentResolver().openInputStream(selectedImage), null, o2);

    }
}
